package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.api.ApiService;
import com.example.myapplication.model.LoginRequest;
import com.example.myapplication.model.LoginResponse;
import com.example.myapplication.network.RetrofitClient;
import com.example.myapplication.utils.TokenManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private TextInputLayout tilUsername, tilPassword;
    private TextInputEditText etUsername, etPassword;
    private MaterialButton btnLogin;
    private TextView tvForgotPassword, tvContactAdmin, tvDemoHint;

    // 智慧温室系统演示账号
    private static final String DEMO_USERNAME = "admin";
    private static final String DEMO_PASSWORD = "123456";
    private static final String DEMO_USERNAME_2 = "greenhouse";
    private static final String DEMO_PASSWORD_2 = "smart2024";

    // 云平台测试账号
    private static final String CLOUD_USERNAME = "13228005663@qq.com";
    private static final String CLOUD_PASSWORD = "13228005663@qq.com";

    // 网络和Token管理
    private ApiService apiService;
    private TokenManager tokenManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        initNetworkComponents();
        setupClickListeners();
        setDefaultCredentials();
    }

    private void initNetworkComponents() {
        // 初始化网络服务和Token管理器
        apiService = RetrofitClient.getInstance(this).getApiService();
        tokenManager = new TokenManager(this);

        // 检查是否已经登录
        if (tokenManager.isLoggedIn()) {
            String username = tokenManager.getUsername();
            Log.d(TAG, "用户已登录: " + username);
            // 可以选择直接跳转到主页面或显示欢迎信息
        }
    }

    /**
     * 设置默认登录凭据
     */
    private void setDefaultCredentials() {
        // 设置默认的云平台账号密码
        etUsername.setText(CLOUD_USERNAME);
        etPassword.setText(CLOUD_PASSWORD);

        // 显示提示信息
        tvDemoHint.setText("💡 已自动填入云平台账号，点击登录即可");
    }

    private void initViews() {
        tilUsername = findViewById(R.id.tilUsername);
        tilPassword = findViewById(R.id.tilPassword);
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvForgotPassword = findViewById(R.id.tvForgotPassword);
        tvContactAdmin = findViewById(R.id.tvContactAdmin);
        tvDemoHint = findViewById(R.id.tvDemoHint);
    }

    private void setupClickListeners() {
        // 登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performLogin();
            }
        });

        // 忘记密码点击事件
        tvForgotPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "请联系系统管理员重置密码", Toast.LENGTH_SHORT).show();
            }
        });

        // 联系管理员点击事件
        tvContactAdmin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "管理员电话: 400-888-6666", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void performLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 清除之前的错误信息
        tilUsername.setError(null);
        tilPassword.setError(null);

        // 验证输入
        if (TextUtils.isEmpty(username)) {
            tilUsername.setError("请输入用户名或工号");
            etUsername.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            tilPassword.setError("请输入密码");
            etPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            tilPassword.setError("密码长度至少6位");
            etPassword.requestFocus();
            return;
        }

        // 检查是否为云平台账号
        if (CLOUD_USERNAME.equals(username) && CLOUD_PASSWORD.equals(password)) {
            // 调用云平台登录API
            performCloudLogin(username, password);
        } else if ((DEMO_USERNAME.equals(username) && DEMO_PASSWORD.equals(password)) ||
                   (DEMO_USERNAME_2.equals(username) && DEMO_PASSWORD_2.equals(password))) {
            // 本地演示账号登录
            performLocalLogin(username);
        } else {
            Toast.makeText(this, "用户名或密码错误，请检查后重试", Toast.LENGTH_SHORT).show();
            showLoginHint();
        }
    }

    /**
     * 执行云平台登录
     */
    private void performCloudLogin(String username, String password) {
        // 禁用登录按钮，防止重复点击
        btnLogin.setEnabled(false);
        btnLogin.setText("登录中...");

        // 创建登录请求
        LoginRequest loginRequest = new LoginRequest(username, password);

        // 调用登录API
        Call<LoginResponse> call = apiService.login(loginRequest);
        call.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                // 恢复登录按钮状态
                btnLogin.setEnabled(true);
                btnLogin.setText("登录");

                if (response.isSuccessful() && response.body() != null) {
                    LoginResponse loginResponse = response.body();
                    String token = loginResponse.getToken();
                    String refreshToken = loginResponse.getRefreshToken();

                    Log.d(TAG, "登录成功，Token: " + (token != null ? token.substring(0, Math.min(20, token.length())) + "..." : "null"));

                    // 保存登录信息
                    tokenManager.saveLoginInfo(token, refreshToken, username);

                    // 显示详细的成功消息，包含token信息
                    String successMessage = "🎉 云平台登录成功！\n\n" +
                            "✅ Token已获取并存储\n" +
                            "📱 Token前20位: " + (token != null ? token.substring(0, Math.min(20, token.length())) + "..." : "null") + "\n" +
                            "💾 已安全保存到本地存储\n\n" +
                            "现在可以使用云平台功能了！";

                    Toast.makeText(MainActivity.this, successMessage, Toast.LENGTH_LONG).show();

                    // 延迟跳转，让用户看到token信息
                    new android.os.Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            navigateToMainActivity(username, true);
                        }
                    }, 1000); // 1秒后跳转

                } else {
                    Log.e(TAG, "登录失败，响应码: " + response.code());
                    Toast.makeText(MainActivity.this, "登录失败，请检查账号密码", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                // 恢复登录按钮状态
                btnLogin.setEnabled(true);
                btnLogin.setText("登录");

                Log.e(TAG, "网络请求失败", t);
                String errorMessage = "网络连接失败: " + t.getMessage();
                Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 执行本地演示账号登录
     */
    private void performLocalLogin(String username) {
        String welcomeMessage = "欢迎进入智慧温室大棚系统！\n用户: " + username;
        Toast.makeText(this, welcomeMessage, Toast.LENGTH_SHORT).show();

        // 跳转到主页面
        navigateToMainActivity(username, false);
    }

    /**
     * 跳转到主页面
     */
    private void navigateToMainActivity(String username, boolean isCloudUser) {
        Intent intent = new Intent(this, GreenhouseMainActivity.class);
        intent.putExtra("username", username);
        intent.putExtra("isCloudUser", isCloudUser);
        if (isCloudUser) {
            intent.putExtra("token", tokenManager.getToken());
        }
        startActivity(intent);
        finish();
    }

    private void showLoginHint() {
        String hint = "可用账号:\n" +
                     "🌟 默认云平台账号: 13228005663@qq.com (已自动填入)\n" +
                     "📱 演示账号: admin / 123456\n" +
                     "🏠 演示账号: greenhouse / smart2024";
        Toast.makeText(this, hint, Toast.LENGTH_LONG).show();
    }
}